/*
 * uart.h
 *
 *  Created on: Dec 21, 2018
 *      Author: zhan
 */

#ifndef HARDWARE_UART_H_
#define HARDWARE_UART_H_


#include "stm32f4xx.h"

#include "gpio_pin.h"

class Uart{

public:
	class Pin{
	private:

	public:
		Pin(GpioPin *tx, GpioPin *rx);
		void init(USART_TypeDef *uartx);
	};

	class Callback{
	public:
		virtual void callback(uint16_t byte);
	};

private:

	GpioPin *tx;
	GpioPin *rx;

	USART_TypeDef *uartx;
	USART_InitTypeDef init_stru;
	Pin *pin;

	Callback*on_received_callback;

	void enable_module(){
		USART_Cmd(uartx,ENABLE);
	}
	void disable_module(){
		USART_Cmd(uartx,DISABLE);
	}
	void set_nvic(){
		NVIC_InitTypeDef NVIC_InitStructure;
		NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
		NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x03;
		NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
		NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
		NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
		NVIC_Init(&NVIC_InitStructure);
	}

public:

	Uart(USART_TypeDef *x, GpioPin *tx, GpioPin *rx, uint32_t baud_rate = 115200,
			uint16_t hardware_flow_control = USART_HardwareFlowControl_None,
			uint16_t mode = USART_Mode_Rx|USART_Mode_Tx,
			uint16_t parity = USART_Parity_No,
			uint16_t stop_bits = USART_StopBits_1,
			uint16_t word_length = USART_WordLength_8b);

	bool init();

	void write(uint8_t *buf, int len);

	void set_on_received_callback(Callback *callback);

	void enable_rx_interrupt(){
		USART_ITConfig(uartx,USART_IT_RXNE,ENABLE);
	}
	void disable_rx_interrupt(){
		USART_ITConfig(uartx,USART_IT_RXNE,ENABLE);
	}

};



#endif /* HARDWARE_UART_H_ */
